import init from './init.js';
import tools from '@/utils/tools.js'
/*
 * @description 上传文件到阿里云oss
 */
class uploadModule {
	constructor() {
		this.uploadPool = null;
		//设置上传缓存
		this.setUploadPool = (event) => {
			this.uploadPool = this.uploadPool ? this.initUploadRaw(this.uploadPool, event) : event;
		}
		//获取上传缓存
		this.getUploadPool = () => {
			return this.uploadPool;
		}
		//初始化属性
		this.initUploadRaw = (row, params) => {
			if (params) {
				let rowKeys = Object.keys(row).concat(Object.keys(params));
				let paramsKeys = Object.keys(params);
				let data = {};
				rowKeys.forEach((item, index) => {
					if (paramsKeys.indexOf(item) > -1) {
						data[item] = params[item];
					} else {
						data[item] = row[item];
					}
				});
				return data;
			} else {
				return tools.deepCopy(row);
			}
		}
		this.formatUploadRaw = (row, params, split = '*') => {
			if (params) {
				if (Array.isArray(params)) {
					if (params && params.length > 0) return params.join(split)
					else return ''
				} else {
					let rowKeys = Object.keys(row);
					let paramsKeys = Object.keys(params);
					let data = {};
					rowKeys.forEach((item, index) => {
						if (paramsKeys.indexOf(item) > -1) {
							data[item] = split ? params[item].join(split) : params[item];
						} else {
							data[item] = row[item];
						}
					});
					return data;
				}
			} else {
				return tools.deepCopy(row);
			}
		}
		//上传文件
		/**
		 * @description 上传文件
		 * @param { Object } options  配置项
		 * @param { Array } files  需要上传的文件
		 * @param { String } method  上传的类型 ['images/','video/','document/']
		 * @param { Number } size  5000000表示5MB以内 默认5MB
		 * @param { String } prefix  需要携带的前缀
		 * @param { String } dir  oss目录
		 * @param { Number } gzip 是否压缩 压缩传百分比数字
		 */
		this.startUpload = (options) => {
			return new Promise(async (resolve, reject) => {
				let initOptions = {
					files: [], //文件数据
					method: '', //['images/','video/','document/']
					size: 5000000, //5000000表示5MB以内 默认5MB
					prefix: '',
					dir: '',
					gzip: '', //是否压缩 压缩传百分比数字
				}
				try {
					initOptions = init.toolsMethods.initRow(initOptions, options);
					console.log(initOptions, 'initOptions');
					if (!initOptions.files || (initOptions.files && initOptions.files.length ===
							0)) {
						resolve()
						return;
						// init.toolsMethods.showTips('上传的文件为空');
						// return;
					}
					init.toolsMethods.showLoading();
					//格式化文件
					init.formatFiles({
						files: initOptions.files,
						size: initOptions.size,
						prefix: initOptions?.prefix
					}).then((formatFile) => {
						let uploadTaskStore = [];
						const date = new Date().format('yyyyMMdd'); // 当前时间 - 年 月 日
						const dateTime = new Date().format('hhmmss'); // 当前时间 - 时 分 秒
						const policyBase64 = init.getPolicyBase64();
						const signature = init.getSignature(policyBase64);

						formatFile.forEach((store) => {
							if (Array.isArray(store)) {
								uploadTaskStore.push(
									store.map((task) => {
										return {
											url: init.env.uploadImageUrl,
											filePath: task.filePath,
											name: 'file',
											formData: {
												'name': initOptions.method +
													initOptions.dir + date +
													'/' + dateTime +
													`_${Math.floor(Math.random() * 150)}` +
													task.name,
												'key': initOptions.method +
													initOptions.dir + date +
													'/' + dateTime +
													`_${Math.floor(Math.random() * 150)}` +
													task.name,
												'policy': policyBase64,
												'OSSAccessKeyId': init.env
													.OSSAccessKeyId,
												'signature': signature,
												'success_action_status': '200',
											},
											source: 0,
										}
									})
								)
							} else {
								uploadTaskStore.push({
									url: init.env.uploadImageUrl,
									filePath: store.filePath,
									name: 'file',
									formData: {
										'name': initOptions.method +
											initOptions.dir + date + '/' +
											dateTime +
											`_${Math.floor(Math.random() * 150)}` +
											store.name,
										'key': initOptions.method +
											initOptions.dir + date + '/' +
											dateTime +
											`_${Math.floor(Math.random() * 150)}` +
											store.name,
										'policy': policyBase64,
										'OSSAccessKeyId': init.env
											.OSSAccessKeyId,
										'signature': signature,
										'success_action_status': '200',
									},
									source: 1,
								})
							}
						})
						let uploadTask = [];
						uploadTaskStore.forEach((taskItem) => {
							uploadTask.push(init.uploadFiles(taskItem, initOptions))
						})
						Promise.all(uploadTask).then((taskResult) => {
							console.log(taskResult, '上传任务回调');
							if (this.uploadPool) {
								let resultKeys = Object.keys(this.uploadPool);
								let result = {};
								resultKeys.forEach((key, index) => {
									result[key] = taskResult[index]
								})
								resolve(result)
							} else {
								resolve(taskResult[0])
							}
							init.toolsMethods.closeLoading();
							this.uploadPool = null;
						}).catch((e) => {
							reject(e);
							console.log(e, '上传失败');
							init.toolsMethods.closeLoading();
						})
					}).catch((error) => {
						console.error(error);
						reject(error);
						init.toolsMethods.closeLoading();
						init.toolsMethods.showTips(JSON.stringify(error))
					})

				} catch (e) {
					//TODO handle the exception
					console.error(e);
					reject(e);
				}
			})
		}
	}
}
export default uploadModule;